package cn.hcbycloud.common.jwt.service.encryptionkey.impl;




import cn.hcbycloud.common.core.constant.CommonConstant;
import cn.hcbycloud.common.jwt.service.encryptionkey.RsaEncryptionKeyService;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

/**
 * @author gaoh
 * @desc 随机生成密钥对接口实现类
 * @date 2022年01月12日 下午 4:32
 */
@SuppressWarnings("all")
public class RsaEncryptionKeyServiceImpl implements RsaEncryptionKeyService {
    @Override
    public Map<String, String> generateKey() throws NoSuchAlgorithmException {
        Map<String, String> keyMap = CollUtil.newHashMap();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        // 生成公钥和私钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 获取公钥对象
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        // 获取私钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        keyMap.put(CommonConstant.PUBLIC_KEY, Base64.encode(publicKey.getEncoded()));
        keyMap.put(CommonConstant.PRIVATE_KEY, Base64.encode(privateKey.getEncoded()));
        return keyMap;
    }
}